package serializable;

import java.io.*;

/**
 * @author dangqi
 * @date 2021/7/27 22:36
 */
public class Test implements Serializable {
    private static final long serialVersionUID = 3005560411086043165L;    
    private int age;    
    private boolean sex;    
    private static class SerializableProxy implements Serializable {      
        private static final long serialVersionUID = 2677759736303136145L;     
        private final int age;       
        private final boolean sex;  
        SerializableProxy(Test test) {       
            this.age = test.age;         
            this.sex = test.sex;     
        }   
    }   
    private void readObject(ObjectInputStream stream) throws InvalidObjectException {
        throw new InvalidObjectException("需要代理!");
    }
    private Object writeReplace() {
        System.out.println("执行了替代方法");
        return new SerializableProxy(this);
    }

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        Test test = new Test();
        test.age = 10;
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
                new FileOutputStream(new File("test")));
        objectOutputStream.writeObject(test);
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test"));
        Test t = (Test)ois.readObject();
        System.out.println(t.age);
    }
}

